<?php

/**
 * trader actions.
 *
 * @package    truetrader
 * @subpackage trader
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class traderActions extends sfActions
{

  public function executeIndex(sfWebRequest $request)
  {
    $this->pager = new sfDoctrinePager(
                    'Trader',
                    sfConfig::get('app_max_trader_page')
    );

    $this->order = $request->getParameter('order');

    $this->sort = $request->getParameter('sort');
    if ($this->sort == 'asc')
    {
      $this->sort = 'desc';
    }
    else if ($this->sort == 'desc')
    {
      $this->sort = 'asc';
    }
    else
    {
      $this->sort = 'asc';
    }

    $this->pager->setQuery(Doctrine::getTable('Trader')->getTraderQuery($this->order, $this->sort));
    $this->pager->setPage($request->getParameter('page', 1));
    $this->pager->init();
  }

  public function executeShow(sfWebRequest $request)
  {
    $user = $this->getRoute()->getObject();
    $this->forward404Unless($this->trader = Doctrine::getTable('Trader')->findOneBy('user_id', $user->id));
    $this->trader_character = Doctrine::getTable('traderCharacter')->find($this->trader->getCharacterId());
  }

  public function executeEdit(sfWebRequest $request)
  {
    $user = $this->getRoute()->getObject();
    $this->forward404Unless($trader = Doctrine::getTable('Trader')->findOneBy('user_id', $user->id));
    $this->form = new TraderForm($trader, array('culture' => $this->getUser()->getCulture()));
    $this->trader_characters = Doctrine::getTable('traderCharacter')->getCharacterList();
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->trader_characters = Doctrine::getTable('traderCharacter')->getCharacterList();
    $this->form = new TraderForm($this->getRoute()->getObject());
    $this->processForm($request, $this->form);
    $this->setTemplate('edit');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $params = $request->getParameter($this->form->getName());
    $year = $params['started']['year'];
    $started = array();
    if ($year != null)
    {
      $started = array('started' => array('day' => 1, 'month' => 1, 'year' => $year));
    }
    $form->bind(array_merge($request->getParameter($form->getName()), $started), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $trader = $form->save();

      $this->redirect('trader', $this->getUser()->getGuardUser());
    }
  }

}
